package com.itcast.flink.window.time;

import org.apache.commons.lang3.time.FastDateFormat;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

/**
 * 滚动时间窗口案例：每5秒钟统计一次，最近5秒内各个路口的通过红路灯汽车的数量
 *
 * @author lilulu
 */
public class TumblingTimeWindowDemo {
    public static void main(String[] args) throws Exception {
        // 1. 执行环境-env
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        // 2. 数据源-source
        DataStreamSource<String> inputStream = env.socketTextStream("node1", 9999);
                    /*
            卡口名称,卡口车流量
            a,3
            a,2
            a,7
            d,9
            b,6
            a,5
            b,3
            e,7
            e,4
             */
        // 3. 数据转换-transformation
        // 3-1. 对数据进行转换处理：过滤脏数据，解析数据封装到二元组中
        SingleOutputStreamOperator<Tuple2<String, Integer>> mapStream = inputStream
                .filter(line -> line.trim().split(",").length == 2)
                .map(new MapFunction<String, Tuple2<String, Integer>>() {
                    @Override
                    public Tuple2<String, Integer> map(String value) throws Exception {
                        System.out.println("item: " + value);
                        String[] split = value.split(",");
                        return Tuple2.of(split[0], Integer.parseInt(split[1]));
                    }
                });
        // 3-2. 设置窗口和函数，将流式数据划分为窗口计算
        // a. 按照卡口名称进行分组
        // b. 设置窗口：滚动时间窗口 size = slide = 5s
        SingleOutputStreamOperator<String> windowStream = mapStream
                .keyBy(tuple -> tuple.f0)
                .window(TumblingProcessingTimeWindows.of(Time.seconds(5)))
                // c. 窗口函数，对窗口内数据处理
                .apply(new WindowFunction<Tuple2<String, Integer>, String, String, TimeWindow>() {
                    private FastDateFormat fastDateFormat = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");

                    /**
                     * @param key        分组key，此处就是卡口名称
                     * @param timeWindow 窗口类型，此处为时间窗口TimeWindow，可以获取窗口开始时间和结束时间
                     * @param iterable   窗口中数据，封装在迭代器中，遍历数据，进行处理
                     * @param collector  窗口计算结果数据收集器，将结果发送到下游
                     * @throws Exception
                     */
                    @Override
                    public void apply(String key, TimeWindow timeWindow, Iterable<Tuple2<String, Integer>> iterable, Collector<String> collector) throws Exception {
                        String windowStart = fastDateFormat.format(timeWindow.getStart());
                        String windowEnd = fastDateFormat.format(timeWindow.getEnd());
                        int sum = 0;
                        for (Tuple2<String, Integer> tuple2 : iterable) {
                            sum += tuple2.f1;
                        }

                        String output = "window: [" + windowStart + " ~ " + windowEnd + "], " + key + " = " + sum;
                        collector.collect(output);
                    }
                });
        // 4. 数据终端-sink
        windowStream.printToErr();
        // 5. 触发执行-execute
        env.execute("TumblingTimeWindowDemo");
    }
}